<template>
  <div class="health-reports-container">
    <div class="page-header">
      <h1>健康报告管理</h1>
      <el-button type="primary" @click="openUploadDialog">
        <el-icon><Upload /></el-icon> 上传健康报告
      </el-button>
    </div>
    
    <el-card v-loading="loading">
      <template #header>
        <div class="card-header">
          <el-input
            v-model="searchQuery"
            placeholder="搜索报告标题"
            clearable
            style="width: 200px"
          />
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            @change="handleDateChange"
          />
        </div>
      </template>
      
      <div v-if="filteredReports.length === 0" class="no-data">
        <el-empty description="暂无健康报告" />
      </div>
      
      <el-table v-else :data="filteredReports" style="width: 100%">
        <el-table-column prop="title" label="报告标题" sortable />
        <el-table-column label="报告日期" sortable>
          <template #default="scope">
            {{ formatDate(scope.row.report_date) }}
          </template>
        </el-table-column>
        <el-table-column prop="description" label="报告描述" show-overflow-tooltip />
        <el-table-column label="上传时间" sortable>
          <template #default="scope">
            {{ formatDate(scope.row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button type="primary" size="small" @click="openEditDialog(scope.row)">
              编辑
            </el-button>
            <el-button type="success" size="small" @click="downloadReport(scope.row)">
              下载
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row.id)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    
    <!-- 上传报告对话框 -->
    <el-dialog
      v-model="uploadDialogVisible"
      title="上传健康报告"
      width="500px"
    >
      <el-form :model="formData" :rules="rules" ref="reportForm" label-width="100px">
        <el-form-item label="报告标题" prop="title">
          <el-input v-model="formData.title" placeholder="请输入报告标题" />
        </el-form-item>
        
        <el-form-item label="报告日期" prop="report_date">
          <el-date-picker
            v-model="formData.report_date"
            type="date"
            placeholder="选择报告日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="报告描述" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            placeholder="请输入报告描述"
            :rows="3"
          />
        </el-form-item>
        
        <el-form-item label="报告文件" prop="report">
          <el-upload
            ref="upload"
            :action="''"
            :auto-upload="false"
            :limit="1"
            :on-change="handleFileChange"
            :on-remove="handleFileRemove"
            :file-list="fileList"
          >
            <template #trigger>
              <el-button type="primary">选择文件</el-button>
            </template>
            <template #tip>
              <div class="el-upload__tip">
                支持格式: jpg, png, pdf, doc, xls 等，大小不超过10MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="uploadDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitUpload" :loading="submitting">
            上传
          </el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 编辑报告对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑健康报告"
      width="500px"
    >
      <el-form :model="editData" :rules="rules" ref="editForm" label-width="100px">
        <el-form-item label="报告标题" prop="title">
          <el-input v-model="editData.title" placeholder="请输入报告标题" />
        </el-form-item>
        
        <el-form-item label="报告日期" prop="report_date">
          <el-date-picker
            v-model="editData.report_date"
            type="date"
            placeholder="选择报告日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="报告描述" prop="description">
          <el-input
            v-model="editData.description"
            type="textarea"
            placeholder="请输入报告描述"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEdit" :loading="submitting">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { useStore } from 'vuex'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Upload } from '@element-plus/icons-vue'
import axios from 'axios'

export default {
  name: 'HealthReports',
  components: {
    Upload
  },
  setup() {
    const store = useStore()
    const reportForm = ref(null)
    const editForm = ref(null)
    const upload = ref(null)
    
    // 数据
    const reports = ref([])
    const loading = ref(false)
    const submitting = ref(false)
    const fileList = ref([])
    
    // 搜索和筛选
    const searchQuery = ref('')
    const dateRange = ref(null)
    const startDate = ref(null)
    const endDate = ref(null)
    
    // 对话框控制
    const uploadDialogVisible = ref(false)
    const editDialogVisible = ref(false)
    const currentId = ref(null)
    
    // 表单数据
    const formData = reactive({
      title: '',
      report_date: '',
      description: '',
      report: null
    })
    
    const editData = reactive({
      title: '',
      report_date: '',
      description: ''
    })
    
    // 表单验证规则
    const rules = {
      title: [
        { required: true, message: '请输入报告标题', trigger: 'blur' }
      ],
      report_date: [
        { required: true, message: '请选择报告日期', trigger: 'change' }
      ]
    }
    
    // 根据搜索和日期范围过滤报告
    const filteredReports = computed(() => {
      let result = reports.value
      
      if (searchQuery.value) {
        const query = searchQuery.value.toLowerCase()
        result = result.filter(item => 
          item.title.toLowerCase().includes(query) || 
          (item.description && item.description.toLowerCase().includes(query))
        )
      }
      
      if (startDate.value && endDate.value) {
        result = result.filter(item => {
          const reportDate = new Date(item.report_date)
          return reportDate >= startDate.value && reportDate <= endDate.value
        })
      }
      
      return result
    })
    
    // 格式化日期
    const formatDate = (dateString) => {
      const date = new Date(dateString)
      return date.toLocaleDateString('zh-CN')
    }
    
    // 处理日期范围变更
    const handleDateChange = (val) => {
      if (val) {
        startDate.value = new Date(val[0])
        endDate.value = new Date(val[1])
      } else {
        startDate.value = null
        endDate.value = null
      }
    }
    
    // 获取所有健康报告
    const fetchReports = async () => {
      loading.value = true
      try {
        const data = await store.dispatch('healthReports/fetchReports')
        reports.value = data
      } catch (error) {
        ElMessage.error('获取健康报告失败')
        console.error(error)
      } finally {
        loading.value = false
      }
    }
    
    // 处理文件变更
    const handleFileChange = (file) => {
      formData.report = file.raw
    }
    
    // 处理文件移除
    const handleFileRemove = () => {
      formData.report = null
    }
    
    // 打开上传对话框
    const openUploadDialog = () => {
      // 重置表单
      Object.keys(formData).forEach(key => {
        formData[key] = key === 'report' ? null : ''
      })
      fileList.value = []
      
      uploadDialogVisible.value = true
    }
    
    // 打开编辑对话框
    const openEditDialog = (row) => {
      currentId.value = row.id
      
      // 填充表单数据
      editData.title = row.title
      editData.report_date = row.report_date
      editData.description = row.description
      
      editDialogVisible.value = true
    }
    
    // 提交上传
    const submitUpload = async () => {
      if (!reportForm.value) return
      
      await reportForm.value.validate(async (valid) => {
        if (valid) {
          if (!formData.report) {
            ElMessage.warning('请选择要上传的文件')
            return
          }
          
          submitting.value = true
          
          try {
            const formDataObj = new FormData()
            formDataObj.append('title', formData.title)
            formDataObj.append('report_date', formData.report_date)
            formDataObj.append('description', formData.description)
            formDataObj.append('report', formData.report)
            
            await store.dispatch('healthReports/uploadReport', formDataObj)
            ElMessage.success('报告上传成功')
            
            // 关闭对话框并刷新数据
            uploadDialogVisible.value = false
            await fetchReports()
          } catch (error) {
            ElMessage.error('上传报告失败')
            console.error(error)
          } finally {
            submitting.value = false
          }
        }
      })
    }
    
    // 提交编辑
    const submitEdit = async () => {
      if (!editForm.value) return
      
      await editForm.value.validate(async (valid) => {
        if (valid) {
          submitting.value = true
          
          try {
            await store.dispatch('healthReports/updateReport', {
              id: currentId.value,
              reportData: editData
            })
            ElMessage.success('报告更新成功')
            
            // 关闭对话框并刷新数据
            editDialogVisible.value = false
            await fetchReports()
          } catch (error) {
            ElMessage.error('更新报告失败')
            console.error(error)
          } finally {
            submitting.value = false
          }
        }
      })
    }
    
    // 下载报告
    const downloadReport = (report) => {
      const filePath = report.file_path
      const fileName = report.title + filePath.substring(filePath.lastIndexOf('.'))
      
      // 创建下载链接
      axios({
        url: `http://localhost:5000/${filePath}`,
        method: 'GET',
        responseType: 'blob'
      })
        .then(response => {
          const url = window.URL.createObjectURL(new Blob([response.data]))
          const link = document.createElement('a')
          link.href = url
          link.setAttribute('download', fileName)
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
        })
        .catch(error => {
          ElMessage.error('下载报告失败')
          console.error(error)
        })
    }
    
    // 删除报告
    const handleDelete = (id) => {
      ElMessageBox.confirm('确定要删除这份健康报告吗？此操作不可逆', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          loading.value = true
          try {
            await store.dispatch('healthReports/deleteReport', id)
            ElMessage.success('健康报告删除成功')
            await fetchReports()
          } catch (error) {
            ElMessage.error('删除健康报告失败')
            console.error(error)
          } finally {
            loading.value = false
          }
        })
        .catch(() => {
          // 取消删除
        })
    }
    
    // 页面加载时获取数据
    onMounted(() => {
      fetchReports()
    })
    
    return {
      reports,
      loading,
      submitting,
      searchQuery,
      dateRange,
      uploadDialogVisible,
      editDialogVisible,
      formData,
      editData,
      rules,
      reportForm,
      editForm,
      upload,
      fileList,
      filteredReports,
      formatDate,
      handleDateChange,
      handleFileChange,
      handleFileRemove,
      openUploadDialog,
      openEditDialog,
      submitUpload,
      submitEdit,
      downloadReport,
      handleDelete
    }
  }
}
</script>

<style scoped>
.health-reports-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0;
  color: #409EFF;
}

.card-header {
  display: flex;
  gap: 15px;
}

.no-data {
  padding: 40px 0;
}
</style> 